"""
SimpleAPI ORM 异常类

提供简化的异常接口，封装 Tortoise ORM 的异常。
用户只需要处理这些异常，无需了解底层的 Tortoise 异常。
"""

from tortoise.exceptions import (
    DoesNotExist as TortoiseDoesNotExist,
    MultipleObjectsReturned as TortoiseMultipleObjectsReturned,
    IntegrityError as TortoiseIntegrityError,
    ValidationError as TortoiseValidationError,
    ConfigurationError as TortoiseConfigurationError,
    TransactionManagementError as TortoiseTransactionManagementError,
    OperationalError as TortoiseOperationalError,
    DBConnectionError as TortoiseDBConnectionError,
)


class ORMError(Exception):
    """ORM 基础异常类"""
    pass


class DoesNotExist(ORMError, TortoiseDoesNotExist):
    """记录不存在异常"""
    pass


class MultipleObjectsReturned(ORMError, TortoiseMultipleObjectsReturned):
    """返回多个对象异常"""
    pass


class IntegrityError(ORMError, TortoiseIntegrityError):
    """数据完整性错误"""
    pass


class ValidationError(ORMError, TortoiseValidationError):
    """数据验证错误"""
    pass


class ConfigurationError(ORMError, TortoiseConfigurationError):
    """配置错误"""
    pass


class TransactionError(ORMError, TortoiseTransactionManagementError):
    """事务管理错误"""
    pass


class DatabaseError(ORMError, TortoiseOperationalError):
    """数据库操作错误"""
    pass


class ConnectionError(ORMError, TortoiseDBConnectionError):
    """数据库连接错误"""
    pass


# 异常映射，用于将 Tortoise 异常转换为我们的异常
EXCEPTION_MAP = {
    TortoiseDoesNotExist: DoesNotExist,
    TortoiseMultipleObjectsReturned: MultipleObjectsReturned,
    TortoiseIntegrityError: IntegrityError,
    TortoiseValidationError: ValidationError,
    TortoiseConfigurationError: ConfigurationError,
    TortoiseTransactionManagementError: TransactionError,
    TortoiseOperationalError: DatabaseError,
    TortoiseDBConnectionError: ConnectionError,
}


def convert_exception(exc: Exception) -> Exception:
    """
    将 Tortoise 异常转换为我们的异常
    
    Args:
        exc: 原始异常
        
    Returns:
        转换后的异常
    """
    exc_type = type(exc)
    if exc_type in EXCEPTION_MAP:
        return EXCEPTION_MAP[exc_type](str(exc))
    return exc 